﻿using System;
using System.Data;
using DHYHN.ASPNET.HoiNghi.DAL;

namespace DHYHN.ASPNET.HoiNghi.BIZ
{
    public class DbHelper
    {
        internal DatabaseDataContext _dataContext;
        internal bool _transactionFlag;
           
        public DbHelper()
        {
            _dataContext=new DatabaseDataContext();
        }

        public DatabaseDataContext DataContext
        {
            get
            {
                if (_dataContext == null)
                    _dataContext = new DatabaseDataContext();
                return _dataContext;
            }
        }

        public void BeginTransaction()
        {
            // Set flag
            _transactionFlag = true;
            // Start _trans
            _dataContext.Connection.Open();
            _dataContext.Transaction = _dataContext.Connection.BeginTransaction();
        }

        public void CommitTransaction()
        {
            // Set flag
            _transactionFlag = false;
            // Start _trans
            if (_dataContext.Transaction != null && _dataContext.Connection.State != ConnectionState.Closed)
            {
                _dataContext.Transaction.Commit();
                _dataContext.Transaction.Dispose();
                _dataContext.Transaction = null;
            }
        }

        public void RollbackTransaction()
        {
            // Set flag
            _transactionFlag = false;
            // Start _trans
            if (_dataContext.Transaction != null && _dataContext.Connection.State != ConnectionState.Closed)
            {
                _dataContext.Transaction.Rollback();
                _dataContext.Transaction.Dispose();
                _dataContext.Transaction = null;
            }
        }

        protected virtual void Dispose(bool isDispose)
        {
            if (isDispose)
            {
                if (_dataContext.Connection.State != ConnectionState.Closed)
                    _dataContext.Connection.Close();
                _dataContext.Dispose();
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}